package codeTop;

import java.util.*;

public class q103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean flag = false;
        while (!queue.isEmpty()) {
            flag = !flag;
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                if (flag) {
                    TreeNode first = queue.getFirst();
                    queue.removeFirst();
                    list.add(first.val);
                    if (first.left != null) queue.offer(first.left);
                    if (first.right != null) queue.offer(first.right);
                }else {
                    TreeNode last = queue.getLast();
                    queue.removeLast();
                    list.add(last.val);
                    if (last.right != null) queue.addFirst(last.right);
                    if (last.left != null) queue.addFirst(last.left);
                }
            }
            res.add(list);
        }
        return res;
    }
}
